<template>
  <div>
      <div class="change-img" @mouseover="stopChange()" @mouseleave="startChange()">
          <div class="img-container">
              <img :src="picture">
          </div>
          <div class="prev" @click="goPrev()">《 </div>
          <div class="next" @click="goNext()"> 》</div>
          <ul class="icon">
              <li class="active" id="li0"></li>
              <li id="li1"></li>
              <li id="li2"></li>
              <li id="li3"></li>
              <li id="li4"></li>
          </ul>
      </div>
      <br>
  </div>
</template>

<script setup>
import {ref,onMounted,onBeforeUnmount } from 'vue'
import axios from '../utils/axios'
onMounted(() => {
  getImages()
})
onBeforeUnmount(() => {
  clearInterval(timerId)
})
let images = [

]
let i = 0
let picture = ref('')
picture.value = images[i]
async function getImages(){
  const {data} = await axios.get('images')
  images = data.data
}
function goNext(){
  if(i<4) i++
  else if(i === 4) i = 0
  document.querySelector('.active').classList.remove('active')
  document.querySelector(`#li${i}`).classList.add('active')
  picture.value = images[i]
}
function goPrev(){
  if(i>0) i--
  else if(i === 0) i = 4
  document.querySelector('.active').classList.remove('active')
  document.querySelector(`#li${i}`).classList.add('active')
  picture.value = images[i]
}
let timerId = 0
timerId = setInterval(() => {
  goNext()
},2000)
function startChange() {
  goNext()
  timerId = setInterval(() => {
    goNext()
  },2000)
}
function stopChange() {
  clearInterval(timerId)
}
</script>

<style scoped>
.change-img{
  width:68%;
  position:relative;
  overflow: hidden;
  margin: auto;
  border-radius: 30px;
}
.img-container{
  /* 图片列表容器宽度：图片高度*图片个数 */
  width:100%;
  display:flex;
}
.img-container img{
  width:100%;
  height:500px;
}
.change-img .prev, .change-img .next{
  position:absolute;
  top:45%;
  width:2%;
  height:6%;
  background: #666;
  color:#fff;
  line-height:30px;
  cursor:pointer;
}
.change-img .prev{
  left:1%;
  text-align:left;
}
.change-img .next{
  right:1%;
  text-align:right;
}
.change-img .icon{
  position:absolute;
  bottom:10px;
  right:42%;
}
.change-img .icon li{
  float:left;
  list-style:none;
  width:20px;
  height:20px;
  background: #666;
  color:#fff;
  margin-left:10px;
  text-align:center;
  line-height:20px;
  border-radius: 50%;
  overflow: hidden;
  cursor:pointer;
}
.change-img .icon li.active{
  background: #fff;
}
</style>